package com.example.controller;

import com.example.enmu.ResultCodeEnum;
import com.example.result.DataResponse;
import com.example.service.CLibrary;
import com.example.service.UHFPrimeService;
import com.example.util.TypeConversionUtil;
import com.sun.jna.ptr.ByteByReference;
import com.sun.jna.ptr.IntByReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;

@RequestMapping("/com")
@RestController
public class ComController {

    @Autowired
    UHFPrimeService uhfPrimeService;

    @PostMapping("/openDevice")
    public DataResponse OpenDevice(@RequestBody HashMap<String,Object> hashMap){
        IntByReference hComm= new IntByReference();
        try {
            System.out.println("进入OpenDevice");
            ArrayList<String> list = uhfPrimeService.execRootCmd("reg query \"HKLM\\SYSTEM\\CurrentControlSet\\Enum\\USB\" /s /v FriendlyName");
            String comPort = list.get(0);
            byte Baudrate = TypeConversionUtil.intTobyte(115200);
            IntByReference intByReference = CLibrary.INSTANCE.OpenDevice(hComm, comPort,new ByteByReference(Baudrate) );
            String data = TypeConversionUtil.typeConversion(intByReference);
            HashMap<String, Object> map = new HashMap<>();
            map.put("hComm",hComm.getValue());
            map.put("data",data);
            if(StringUtils.isEmpty(data)){
                map.put("data",TypeConversionUtil.success);
            }
            map.put("log",null);
            map.put("msgB",null);
            map.put("res_code",1000);
            CLibrary.INSTANCE.CloseDevice(hComm.getValue());
            return new DataResponse<>(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  new DataResponse(ResultCodeEnum.SYSTEM_ERROR, "Abnormal interface");
    }

}
